#include "board.h"

#define TAG "BOARD"

const i2c_config_t i2c_config[] = {
    {.mode = I2C_MODE_MASTER, .sda_io_num = I2C0_SDA_IO, .scl_io_num = I2C0_SCL_IO, 
        .sda_pullup_en = GPIO_PULLUP_ENABLE, .scl_pullup_en = GPIO_PULLUP_ENABLE, .master.clk_speed = 100000 },\
    
};

void board_init()
{
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    for (int i = I2C_NUM_0; i < sizeof(i2c_config) / sizeof(i2c_config_t); i++) {
        i2c_param_config(i, &i2c_config[i]);
        i2c_driver_install(i, i2c_config[i].mode, 0, 0, 0);
    }
}

void manager_init()
{   
    input_manager_init();

    lvgl_manager_init();

    fs_manager_init();

    hotplug_manager_init();

    audio_manager_init();

    ui_manager_init();

    task_manager_init();
}

/* 外部IO口在driver_init之后才能调用 */
void sys_set_pa_level(uint8_t level)
{
    struct device *exio = device_get_binding("pca9557");
    if (!exio) { 
        ESP_LOGE(TAG, "Failed to get pca9557 device");
        return;
    }

    exio_config(exio, PA_EN_IO, EXT_IO_MODE_OUTPUT);
    exio_set_level(exio, PA_EN_IO, level);
}

void sys_set_lcd_cs_level(uint8_t level)
{
    struct device *exio = device_get_binding("pca9557");
    if (!exio) { 
        ESP_LOGE(TAG, "Failed to get pca9557 device");
        return;
    }

    exio_config(exio, LCD_CS_IO, EXT_IO_MODE_OUTPUT);
    exio_set_level(exio, LCD_CS_IO, level);
}

void sys_set_dvp_pwdn_level(uint8_t level)
{
    struct device *exio = device_get_binding("pca9557");
    if (!exio) { 
        ESP_LOGE(TAG, "Failed to get pca9557 device");
        return;
    }

    exio_config(exio, DVP_PWDN_IO, EXT_IO_MODE_OUTPUT);
    exio_set_level(exio, DVP_PWDN_IO, level);
}

